package com.tool.finances.lifestyle;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.tool.finances.lifestyle.data.AccountProvider;
import com.tool.finances.lifestyle.data.AccountType;
import com.tool.finances.lifestyle.data.AccountType.Account;

public class FinancesTabActivity extends Activity {

	public static final int INCOME_TAG = 0;
	public static final int OUTCOME_TAG = 1;
	private int ID = 0;

	private String[] categoryItems;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Button incomeButton = (Button) findViewById(R.id.Button01);
		incomeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(INCOME_TAG);
			}
		});

		Button outcomeButton = (Button) findViewById(R.id.Button02);
		outcomeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(OUTCOME_TAG);
			}
		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		ID = id;

		Cursor cursor = getContentResolver().query(
				AccountProvider.CATEGORY_CONTENT_URI,
				AccountType.Account.CATEGORYPROECTION, null, null, "");
		categoryItems = getItemArray(cursor);
		return new AlertDialog.Builder(FinancesTabActivity.this).setTitle(
				R.string.choose_category)// R.array.category
				.setItems(categoryItems, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

						if (categoryItems[which].equalsIgnoreCase("New")) {// items[which]
							Intent i = new Intent(FinancesTabActivity.this,
									AddCategory.class);
							i.putExtra("AccountTag", ID);
							startActivity(i);
						} else {
							Intent intent = new Intent(
									FinancesTabActivity.this,
									AccountActivity.class);
							intent.putExtra("AccountTag", ID);
							intent.putExtra("AccountCategory",
									categoryItems[which]);// items[which]
							startActivity(intent);
						}

						dialog.dismiss();
						// finish();
					}
				})//
				.create();
	}

	private String[] getItemArray(Cursor cursor) {
		int count = cursor.getCount();
		String[] stringsItem = new String[count];
		int i = 0;
		if (cursor.moveToFirst()) {
			do {
				int index = cursor.getColumnIndex(Account.CATEGORYTYPE);
				stringsItem[i] = cursor.getString(index);
				i++;
			} while (cursor.moveToNext());
		}
		return stringsItem;
	}
}
